package com.easypay.reactive8583.netty.pipeline;

import com.easypay.reactive8583.iso.MessageClass;
import com.easypay.reactive8583.iso.MessageFactory;
import com.easypay.reactive8583.iso.MessageFunction;
import com.easypay.reactive8583.iso.MessageOrigin;
import com.solab.iso8583.IsoMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author pandans
 * @date 2021/03/04 15:51
 * @Description:
 */
public class IdleEventHandler extends ChannelInboundHandlerAdapter {
    private MessageFactory<IsoMessage> isoMessageFactory;

    public IdleEventHandler(MessageFactory<IsoMessage> isoMessageFactory) {
        this.isoMessageFactory = isoMessageFactory;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.READER_IDLE || idleStateEvent.state() == IdleState.ALL_IDLE) {
                IsoMessage echoMessage = createEchoMessage();
                ctx.write(echoMessage);
                ctx.flush();
            }
        }
        super.userEventTriggered(ctx, evt);
    }
    private IsoMessage createEchoMessage()  {
        return isoMessageFactory.newMessage( MessageClass.NETWORK_MANAGEMENT, MessageFunction.REQUEST, MessageOrigin.ACQUIRER);
    }
}
